import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import UniStorage from '@/utils/storage'
interface UserInfo {
  appid: string
  headimgurl: string
  nickname: string
  openid: string
  unionid: string
  uid: string
  session_id: string
  session_key: string
}

const initState: UserInfo = {
  appid: '',
  headimgurl: '',
  nickname: '',
  openid: '',
  unionid: '',
  uid: '',
  session_id: '',
  session_key: '',
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo>({ ...initState })

  const setUserInfo = (val: UserInfo) => {
    userInfo.value = val
  }

  const getUserInfo = () => {
    return userInfo.value
  }

  const clearUserInfo = () => {
    userInfo.value = { ...initState }
  }

  const updateUserInfo = <K extends keyof UserInfo>(key: K, value: UserInfo[K]) => {
    userInfo.value[key] = value
    console.log('getUserInfo() --->', getUserInfo())
    UniStorage.setItem('userInfo', getUserInfo())
  }

  const isLoggedIn = computed(() => !!userInfo.value.openid)

  return {
    userInfo,
    getUserInfo,
    setUserInfo,
    clearUserInfo,
    updateUserInfo,
    isLoggedIn,
  }
})
